package com.leenmvc.core.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.leenmvc.core.config.filter.GlobalFilter;
import com.leenmvc.core.config.filter.HttpServletRequestReplacedFilter;
import com.leenmvc.core.config.filter.ThreadHeadFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

import java.util.Properties;

/**
 * 生成验证码配置
 *
 * @author leen
 */
@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.font.names", "Arial,Courier,宋体,楷体,微软雅黑");
        properties.put("kaptcha.textproducer.char.space", "5");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

    /**
     * 主过滤器
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean globalFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new GlobalFilter());
        bean.addUrlPatterns("/*");
        return bean;
    }
    /**
     * 线程头部在最开始的时候执行
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean headFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new ThreadHeadFilter());
        bean.setOrder(1);
        bean.addUrlPatterns("/*");
        return bean;
    }



    /**
     * 注冊filter包裝類用于处理不能在filter中进行转发的问题
     *
     * @return
     *
     */
    @Bean
    public FilterRegistrationBean delegatingFilterProxy() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        DelegatingFilterProxy proxy = new DelegatingFilterProxy();
        proxy.setTargetFilterLifecycle(true);
        proxy.setTargetBeanName("shiroFilter");
        filterRegistrationBean.setFilter(proxy);
        return filterRegistrationBean;
    }

    /**
     * 将保存request流的拦截器注册进来
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBeanForRequestBody() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new HttpServletRequestReplacedFilter());
        bean.addUrlPatterns("/*");
        return bean;
    }
}
